const Controller = require('egg').Controller;
const moment = require('moment')

/**@namespace app.io.controller.data */
class DataController extends Controller {

  /** 接收列表数据 */
  async receivePageData() {
    const page = this.ctx.args[0];

    //普通模式 + 还有下一页 分发采集下一页的任务
    if (!page.test && page.hasNextPage) {
      this.ctx.service.spiderTask.randomSendTask(
        {
          platform: page.platform,
          type: 'page',
          data: page.nextPage,
        });
    }

  }

  /** 接收 标签 直播间数据 */
  async receiveTagData() {
    const page = this.ctx.args[0];

    //普通模式 + 还有下一页 分发采集下一页的任务
    if (!page.test && page.hasNextPage) {
      this.ctx.service.spiderTask.randomSendTask(
        {
          platform: page.platform,
          type: 'tag',
          data: {page: page.nextPage, tag: page.tag, type: page.type},
        });
    }
  }

  /** 采集遇到错误，再次尝试 */
  async retry() {
    const task = this.ctx.args[0];
    let retry = task.retry;
    console.log('重试', task);
    if (retry > 0) {
      if (retry >= 3) {
        await this.ctx.service.saveError.save(task.error);
        return;
      }
      retry++;
    } else {
      retry = 1;
    }
    this.ctx.service.spiderTask.randomSendTask(
      {
        platform: task.platform,
        type: task.type,
        retry,
        data: task.data,
      });
  }

  /** 接收直播间信息 */
  async receiveRoomData() {
    const room = this.ctx.args[0];
    this.ctx.service.spiderTask.saveData(room);
  }

  /** 明日之后 调试*/
  async debug() {
    const room = this.ctx.args[0];
    const now = moment().format('YYYY-MM-DD');

    const room_id = room.anchor.room;
    const platform_id = room.platform.id;
    const platform_tag = room.platform.tag;

    const key = platform_id + '_' + room_id;

    await this.app.redis.hset('debug:' + now, key, JSON.stringify({
      id: room.anchor.room,
      name: room.anchor.name,
      type: room.type,
      platform: platform_tag
    }));

  }
}

module.exports = DataController;